#include<avr/io.h>
#include"spi.h"


void spi_init(void)
{
  static unsigned char spi_inited = 0;

  if (spi_inited)
    return;

  DRIVER(SPI_MISO,IN);		//as input
  DRIVER(SPI_MISO,PULLUP);	// with pullup

  /* Initalize ports for communication with SPI units. */
  /* CSN=SS and must be output when master! */
  DRIVER(SPI_MOSI,OUT);
  DRIVER(SPI_SCK,OUT);
  DRIVER(CC_SS,OUT);



  /* Enables SPI, selects "master", clock rate FCK / 2, and SPI mode 0 */
  SPCR = BV(SPE) | BV(MSTR);
  SPSR = BV(SPI2X);
}


uint8_t spi_write_single(uint8_t byte) {
    uint8_t ret;
    SPI_TX_BUF = byte;
    WAIT_EORX();
    ret = SPI_RX_BUF;
    return ret;
}

uint8_t spi_read_single(void) {
    return spi_write_single(0xDB);
}

uint8_t spi_write(uint8_t* data, int16_t len) {
    uint8_t ret;
    int16_t i;
    
    for (i=0; i<len; i++) {
        SPI_TX_BUF = data[i];
        WAIT_EORX();
        ret = SPI_RX_BUF;
    }
    return ret;
}
void spi_read(uint8_t* data, int16_t len) {
    int16_t i;    
    for (i=0; i<len; i++) {
        SPI_TX_BUF = 0xDB;
        WAIT_EORX();
        data[i] = SPI_RX_BUF;
    }
}


